#include "tourcreator.h"
#include "scenecreator.h"
#include "scenedefinition.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QDebug>
#include <QImage>
#include <QProcess>
#include <opencv/cv.h>
#include <opencv/highgui.h>

tourCreator::tourCreator(tourDefinition tourDef){
    itsDefinition = tourDef;
    src.setPath(QCoreApplication::applicationDirPath());
}

void tourCreator::createItself(){
    if(itsDefinition.valid){
        
        //creating output directory
        QDir output = itsDefinition.tourDir;
        createDirectory(output.path());
        
        //creating thumbnails
        double step = 100.0/itsDefinition.scenes.size();
        for(int i=0;i<itsDefinition.scenes.size();i++){
            emit sign_processPercentage((int)(i*step));

            QString sceneName = itsDefinition.scenes.at(i)->name;
            QString frontPath = output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_f.jpg";
            IplImage* front = cvLoadImage(frontPath.toStdString().c_str());
            CvSize thumbsize = cvSize(50,50);
            IplImage* thumb = cvCreateImage(thumbsize,front->depth,front->nChannels);
            cvResize(front,thumb);
            QString thumbName = output.path()+"/"+sceneName+"_tur/"+sceneName+"_thumb_thumb.jpg";
            cvSaveImage(thumbName.toStdString().c_str(),thumb);
            
            
            //image sizes should be inserted dynamicaly to the cube2sphere.pto
            QString tmplt = readTemplate("./templates/cube2sphere.pto");
            tmplt.replace("$width",QString::number(front->width));
            tmplt.replace("$height",QString::number(front->height));
            saveTemplate(tmplt,"./tmp/cube2sphere.pto");
            
            
            //creating thumbnails
            QString nonaCommand = "nona -o ./tmp/"+ sceneName+".jpg ./tmp/cube2sphere.pto";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_f.jpg ";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_r.jpg ";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_b.jpg ";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_l.jpg ";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_u.jpg ";
            nonaCommand+=" "+output.path()+"/"+sceneName+"_tur/"+sceneName+"/"+sceneName+"_d.jpg ";
            
            qDebug()<<"nonaCommand: "<<nonaCommand;
            
            QString enblendCommand = "enblend -l1 --fine-mask --no-optimize -o "+output.path()+"/"+sceneName+"_tur/"+sceneName+"_thumb.jpg";
            for(int j=0;j<6;j++){
                enblendCommand+=" ./tmp/"+sceneName+".jpg"+"000";
                enblendCommand.append(j+'0');
                enblendCommand+=".tif";
            }
            
            QProcess *myProcess = new QProcess();
            myProcess->execute(nonaCommand);
            myProcess->execute(enblendCommand);
            delete myProcess;

        }
        
        //copying required files
        copyRequiredFiles();

        //filling tour.xml
        QString tmplt = readTemplate(itsDefinition.templateFile.filePath());
        tmplt = fillTemplate(tmplt);
        saveTemplate(tmplt,itsDefinition.tourDir.path()+"/tour.xml");

        //copying tour.html
        tmplt = readTemplate(itsDefinition.templateFile.path()+"/tourhtmltemplate.xml");
        saveTemplate(tmplt,itsDefinition.tourDir.path()+"/tour.html");

        //filling index.html
        tmplt = readTemplate(itsDefinition.templateFile.path()+"/indexhtmltemplate.xml");
        tmplt = fillTemplate(tmplt);
        saveTemplate(tmplt,itsDefinition.tourDir.path()+"/index.html");

        emit sign_processPercentage(100);
    }
}

void tourCreator::createDirectory(QString dirPath){
    if(!QDir().exists(dirPath)){
        QDir().mkpath(dirPath);
    }
}

void tourCreator::copyFile(QFile* file,QDir dir){
    if(!file->open(QIODevice::ReadOnly)) {
        return;
    }
    
    QTextStream in(file);
    QString text="";
    while(!in.atEnd()) {
        text+= in.readLine();
        text+="\n";
    }
    
    file->close();
    
    QFile file2(dir.absolutePath()+"/"+file->fileName().section("/",-1,-1));
    file2.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file2);
    out << text;
    file2.close();
}

#ifdef Q_OS_WIN32

void tourCreator::copyRequiredFiles(){
    QDir dir = itsDefinition.tourDir;
    QString command="xcopy "+src.absolutePath()+"/templates/required"+" "+dir.absolutePath();
    command.replace("/","\\");
    command+=" /e /y";
    system(command.toLatin1().data());
}

#endif
#ifdef Q_OS_LINUX

void tourCreator::copyRequiredFiles(){
    QDir dir = itsDefinition.tourDir;
    QDir dir2 = src.absolutePath()+"/templates/required";
    QStringList files = dir2.entryList();
    for(int i=0;i<files.size();i++){
        QString name = files.at(i);
        if(name.at(0)!='.'){
            QString command="cp -r "+src.absolutePath()+"/templates/required/"+files.at(i)+" "+dir.absolutePath();
            QProcess *myProcess = new QProcess();
            myProcess->execute(command);
            delete myProcess;
        }

    }
}

#endif

QString tourCreator::readTemplate(QString filePath){
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly)) {
        return NULL;
    }
    
    QTextStream in(&file);
    QString text="";
    while(!in.atEnd()) {
        text+= in.readLine();
        text+="\n";
    }
    
    file.close();
    return text;
}

QString tourCreator::fillTemplate(QString tmplt){
    for(int i=0;i<2;i++){
        QString includeScene = "";
        QString sliderPage = "\n";
        for(int i=0;i<itsDefinition.scenes.size();i++){
            QString name = itsDefinition.scenes.at(i)->name;
            includeScene += "<include url=\""+name+"_tur/"+name+"/"+name+".xml\" />\n	";

            sliderPage += "			<a href=\"tour.html?sceneName="+name+"\" rel=\"shadowbox[Galeri1];height=500;width=800\"   >\n";
            sliderPage += "				<img src=\""+name+"_tur/"+name+"_thumb.jpg\" alt=\"\" title=\""+name+"\" />\n";
            sliderPage += "			</a>\n";
        }
        tmplt.replace("$includeScenes",includeScene);
        tmplt.replace("$slides",sliderPage);

    }
    return tmplt;
}

void tourCreator::saveTemplate(QString tmplt,QString filePath){
    QFile file(filePath);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << tmplt;
    file.close();
}

int tourCreator::emptyTmpFolder(){
    QString command = "rm -r ./tmp";
    QString command2 = "mkdir tmp";
    QProcess *myProcess = new QProcess();
    myProcess->execute(command);
    myProcess->execute(command2);
    delete myProcess;
}
